package com.wu.store.service.impl;

import com.github.pagehelper.PageHelper;
import com.wu.store.common.util.FileUtils;
import com.wu.store.dao.CartDao;
import com.wu.store.dao.GoodsDao;
import com.wu.store.entity.*;
import com.wu.store.service.GoodsService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class GoodsServiceImpl implements GoodsService {

    @Autowired
    private GoodsDao goodsDao;

    @Autowired
    private CartDao cartDao;

    @Override
    public List<Goods> getList(GoodsParams goodsParams) {
        if (goodsParams.getMinPrice() == null) {
            goodsParams.setMinPrice(Integer.MIN_VALUE);
        }
        if (goodsParams.getMaxPrice() == null) {
            goodsParams.setMaxPrice(Integer.MAX_VALUE);
        }
        String keyword = goodsParams.getKeyword();
        Long categoryId = goodsParams.getCategoryId();
        if (categoryId == null) {

        } else if (categoryId == 0L) {
            categoryId = null;
            if (StringUtils.isEmpty(keyword)) {
                List<String> searchKeyword = goodsDao.getSearchKeyword(goodsParams.getUid());
                if (searchKeyword.size() > 0) {
                    keyword = StringUtils.join(searchKeyword, "|");
                }
            }
        }
        if (StringUtils.isEmpty(keyword)) {
            keyword = null;
        }
        boolean defaults = StringUtils.isEmpty(goodsParams.getKeyword()) && StringUtils.isNotEmpty(keyword);
        if (!defaults) {
            PageHelper.startPage(goodsParams.getPage(), goodsParams.getSize());
        }
        List<Goods> list = goodsDao.list(
                goodsParams.getStatus(),
                categoryId,
                goodsParams.getMinPrice(),
                goodsParams.getMaxPrice(),
                keyword
        );
//        if (defaults) {
//            String[] split = StringUtils.split(keyword, "|");
//            list.sort(new Comparator<Goods>() {
//                @Override
//                public int compare(Goods o1, Goods o2) {
//                    int s1 = -1;
//                    int s2 = -1;
//                    for (int i = 0; i < split.length; i++) {
//                        String key = split[i];
//                        if (s1 == -1) {
//                            if (o1.getName().contains(key)) {
//                                s1 = i;
//                            }
//                        }
//                        if (s2 == -1) {
//                            if (o2.getName().contains(key)) {
//                                s2 = i;
//                            }
//                        }
//                        if (s1 != -1 && s2 != -1) {
//                            break;
//                        }
//                    }
//                    return s2 - s1;
//                }
//            });
//        }

        if (goodsParams.getUid() != null && list.size() != 0 && StringUtils.isNotEmpty(goodsParams.getKeyword())) {
            List<SearchRecord> recordIdList = goodsDao.getRecordIdList(goodsParams.getKeyword(), goodsParams.getUid());
            if (recordIdList.size() == 0) {
                goodsDao.saveSearchRecord(goodsParams.getUid(), categoryId, goodsParams.getKeyword());
            }
        }
        return list;
    }

    @Override
    public List<Goods> getHotList() {
        return goodsDao.listOrderBySellCount();
    }

    @Override
    public GoodsWithImgList getGoodsInfo(Long id, Cart cart) throws Exception {
        GoodsWithImgList goods = goodsDao.selectById(id);
        if (goods == null) {
            throw new Exception("该商品不存在");
        }
        List<Img> imgList = new ArrayList<>();
        if (StringUtils.isNotEmpty(goods.getImg())) {
            Img img = new Img();
            img.setId(0L);
            img.setGoodsId(goods.getId());
            img.setImg(goods.getImg());
            imgList.add(img);
        }
        List<Img> secondImgList = goodsDao.getImgList(id);
        imgList.addAll(secondImgList);
        goods.setImgList(imgList);
        if (cart != null) {
            Cart cartDetail = cartDao.selectById(cart);
            goods.setCartCount(cartDetail.getGoodsCount());
        }
        return goods;
    }

    @Override
    public boolean isNameValid(Goods goods) throws Exception {
        Goods target = goodsDao.selectByName(goods.getName(), 1);
        if (target == null) return true;
        if (!target.getId().equals(goods.getId())) {
            throw new Exception("该商品名称已被占用");
        }
        return true;
    }

    @Override
    @Transactional
    public void save(GoodsWithImgList goods) throws Exception {
        List<Img> imgList = goods.getImgList();
        List<Img> newImgList = new ArrayList<>();
        String firstImg = null;
        List<Long> imgIdList = new ArrayList<>();
        for (Img img : imgList) {
            if (StringUtils.isNotEmpty(firstImg)) {
                if (img.getId() != null) {
                    imgIdList.add(img.getId());
                } else {
                    img.setImg(FileUtils.generateFile(img.getImg(), goods.getName()));
                    newImgList.add(img);
                }
            }
            if (StringUtils.isEmpty(firstImg) && StringUtils.isNotEmpty(img.getImg())) {
                firstImg = FileUtils.generateFile(img.getImg(), goods.getName());
            }
        }
        goods.setImg(firstImg);
        if (goods.getId() != null) {
            goods.setUpdateTime(new Date());
            goodsDao.update(goods);
        } else {
            goods.setCreateTime(new Date());
            goodsDao.add(goods);
        }
        if (imgIdList.size() == 0) {
            imgIdList = null;
        }
        goodsDao.deleteGoodsImg(goods.getId(), imgIdList);
        if (newImgList.size() > 0) {
            int affectedRows = goodsDao.updateGoodsImg(goods.getId(), newImgList);
            if (affectedRows == 0) {
                throw new Exception("保存图片失败");
            }
        }
    }

    @Override
    public boolean delete(Long id) throws Exception {
        GoodsWithImgList goods = getGoodsInfo(id, null);
        goods.setStatus(0);
        save(goods);
        return true;
    }


}
